﻿using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

namespace DataTableToEntityClass
{
    /// <summary>
    /// 数据库操作虚拟类
    /// <remarks></remarks>
    /// </summary>
    public static class SqlHelper
    {

        /// <summary>
        /// 执行SQL命令，并返回受影响的行数(不再支持存储过程)
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdText">SQL语句</param>
        /// <param name="commandParameters">参数</param>
        /// <returns>返回数据库受影响的函数</returns>
        /// <remarks></remarks>
        public static int ExecuteNonQuery(string connectionString, string cmdText,
            params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, CommandType.Text, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }
        /// <summary>
        /// 执行存储过程(支持Output参数)
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="storedProcedureName">存储过程名</param>
        /// <param name="output">返回参数hash表</param>
        /// <param name="commandParameters">参数</param>
        /// <returns>存储过程操作的返回值</returns>
        /// <remarks></remarks>
        public static int ExecuteStoredProcedure(string connectionString, string storedProcedureName, ref Hashtable output, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, CommandType.StoredProcedure, storedProcedureName, commandParameters);
                //--------------存储过程操作的返回值----------------------
                SqlParameter parameter = new SqlParameter();
                parameter.ParameterName = "@Value";
                parameter.SqlDbType = SqlDbType.Int;
                parameter.Direction = ParameterDirection.ReturnValue;
                cmd.Parameters.Add(parameter);
                //--------------------------------------------------------
                cmd.ExecuteNonQuery();

                int val = Convert.ToInt32(cmd.Parameters["@Value"].Value);
                //----------------------处理返回参数----------------------
                foreach (SqlParameter parm in cmd.Parameters)
                {
                    if (parm.Direction == ParameterDirection.Output)
                    {
                        output.Add(parm.ParameterName, parm.Value);
                    }
                }
                //--------------------------------------------------------
                cmd.Parameters.Clear();
                return val;
            }
        }
        /// <summary>
        /// 执行命令，并返回一个结果集
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">执行类型</param>
        /// <param name="cmdText">存储过程名字或SQL语句</param>
        /// <param name="commandPareters">参数</param>
        /// <returns>返回一个结果集</returns>
        /// <remarks></remarks>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandPareters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandPareters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception ex)
            {
                conn.Close();
                var msg = ex.Message;
                throw;
            }
        }

        /// <summary>
        /// 执行查询，并返回结果集第一行第一列
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">执行类型</param>
        /// <param name="cmdText">存储过程名字或SQL语句</param>
        /// <param name="commParemeters">参数</param>
        /// <returns>结果集第一行第一列</returns>
        /// <remarks></remarks>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commParemeters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commParemeters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 执行命令前准备
        /// </summary>
        /// <param name="cmd">数据库执行对象</param>
        /// <param name="conn">数据库连接对象</param>
        /// <param name="trans">数据库事务</param>
        /// <param name="cmdType">执行类型</param>
        /// <param name="cmdText">存储过程名字或SQL语句</param>
        /// <param name="cmdParms">SQL参数</param>
        /// <remarks></remarks>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType,
            string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
        }

        /// <summary>
        /// 执行查询的SQL语句
        /// </summary>
        /// <param name="strSql">SQL语句</param>
        /// <returns></returns>
        public static DataSet sqlSelectDS(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commParemeters)
        {
            SqlCommand cmd = new SqlCommand();

            DataSet ds = new DataSet();//定义一个容器ds
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commParemeters);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);//实例化SqlDataAdapter对象
                sda.Fill(ds);//填充数据
                return ds;//返回DataSet
            }
        }

        /// <summary>
        /// 执行多条SQL语句,并使用事务
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="sqlStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        /// <returns></returns>
        public static int ExecuteNonQueryWithTransaction(string connectionString, Hashtable sqlStringList)
        {
            int count = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                SqlTransaction trans = conn.BeginTransaction();

                try
                {
                    foreach (DictionaryEntry dictionaryEntry in sqlStringList)
                    {
                        string cmdText = dictionaryEntry.Key.ToString();
                        SqlParameter[] parameters = (SqlParameter[])dictionaryEntry.Value;
                        PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, parameters);
                        count += cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch(Exception ex)
                {
                    ex.ToString();
                    trans.Rollback();
                    count = 0;
                }

            }
            return count;
        }

        /// <summary>
        /// 执行多条SQL语句,并使用事务
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="sqlStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        /// <param name="erro">返回错误信息</param>
        /// <returns></returns>
        public static int ExecuteNonQueryWithTransaction(string connectionString, Hashtable sqlStringList, out string erro)
        {
            int count = 0;
            erro = "";
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                SqlTransaction trans = conn.BeginTransaction();

                try
                {
                    foreach (DictionaryEntry dictionaryEntry in sqlStringList)
                    {
                        string cmdText = dictionaryEntry.Key.ToString();
                        SqlParameter[] parameters = (SqlParameter[])dictionaryEntry.Value;
                        PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, parameters);
                        count += cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch (Exception exception)
                {
                    erro = exception.Message;
                    trans.Rollback();
                    count = 0;
                }

            }
            return count;
        }

        /// <summary>
        /// 执行多条SQL语句,并使用事务返回受影响的行数(有序)
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="sqlStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static int ExecuteNonQueryWithTransaction(string connectionString, IDictionary<string, SqlParameter[]> sqlStringList)
        {
            int count = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                SqlTransaction trans = conn.BeginTransaction();

                try
                {

                    foreach (var dictionaryEntry in sqlStringList)
                    {
                        string cmdText = dictionaryEntry.Key.ToString();
                        SqlParameter[] parameters = (SqlParameter[])dictionaryEntry.Value;
                        PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, parameters);
                        count += cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    ex.ToString();
                    trans.Rollback();
                    count = 0;
                }

            }
            return count;
        }

        /// <summary>
        /// 执行多条SQL语句(有序),使用事务并返回受影响的行数(如果其中一条出现影响行数0,都视为失败)
        /// <remarks></remarks>
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="sqlStringList">SQL语句的哈希表（key为sql语句，value是该语句的SqlParameter[]）</param>
        /// <returns>返回受影响的行数</returns>
        public static int ExecuteNonQueryWithTransactionZeroFail(string connectionString, IDictionary<string, SqlParameter[]> sqlStringList)
        {
            int count = 0;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand cmd = conn.CreateCommand();
                SqlTransaction trans = conn.BeginTransaction();

                try
                {
                    int indentity = 0;
                    foreach (var dictionaryEntry in sqlStringList)
                    {
                        string cmdText = dictionaryEntry.Key.ToString();
                        SqlParameter[] parameters = dictionaryEntry.Value;
                        foreach (SqlParameter q in parameters)
                        {
                            if (q.Direction == ParameterDirection.InputOutput)
                            {
                                q.Value = indentity;
                            }
                        }
                        PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, parameters);
                        int r = cmd.ExecuteNonQuery();
                        if (r == 0)
                        {
                            //无影响行数语句,是异常的
                            trans.Rollback();
                            return 0;
                        }
                        count += r;
                        foreach (SqlParameter q in parameters)
                        {
                            if (q.Direction == ParameterDirection.Output)
                            {
                                indentity = Convert.ToInt32(q.Value);
                            }
                        }
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch (Exception e)
                {
                    trans.Rollback();
                    count = 0;

#if DEBUG
                    throw e;
#endif
                }

            }
            return count;
        }

        /// <summary>
        ///  数据库查询null处理
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object FromDbValue(object value)
        {
            if (value == DBNull.Value)
            {
                return null;
            }
            else
            {
                return value;
            }
        }
        /// <summary>
        /// 插入数据库之前null处理
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static object ToDbValue(object value)
        {
            if (value == null)
            {
                return DBNull.Value;
            }
            else
            {
                return value;
            }
        }
        /// <summary>
        /// 数据库值转换为指定类型,自带DBnull判断
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="o"></param>
        /// <returns></returns>
        public static T DBValueToTypeValue<T>(this object o)
        {
            return o == DBNull.Value ? default(T) : (T)o;
        }
    }
}
